
package com.scs.application.modules.msg.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.modules.msg.entity.Receive;
import com.scs.application.modules.msg.request.ReceiveQueryRequest;
import com.scs.application.modules.msg.service.ReceiveService;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 我的消息 controller
 */
@AllArgsConstructor
@RestController
@RequestMapping("/msg/receives")
public class ReceiveController extends CrudController<Receive, String, ReceiveService> implements ImAndExAbleController<ReceiveQueryRequest> {


    @GetMapping("/page")
    public PageResult page(ReceiveQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/unread")
    public PageResult unRead(ReceiveQueryRequest request) {
        IPage page = service.unReadPage(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/unreadCount")
    public CommonResult getUnReadCount(ReceiveQueryRequest request) {
        List<Receive> list = service.unReadList(request);
        return CommonResult.ok("查询成功", list.stream().map(Receive::getGmtCreate).collect(Collectors.toList()));
    }

    @GetMapping("/list")
    public CommonResult list(ReceiveQueryRequest request) {
        List<Receive> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    @Override
    @DeleteMapping("/{id}")
    public CommonResult deleteById(@PathVariable("id") String id) {
        boolean bRemove = service.removeCascadeById(id);
        return bRemove ? CommonResult.ok("删除成功") : CommonResult.error("删除失败");
    }

    @PutMapping("/updateReadStates")
    @ResponseBody
    public CommonResult updateReadStates(@RequestBody String[] ids) {

        Collection<Receive> receiveList = service.listByIds(Lists.newArrayList(ids));

        receiveList.stream().forEach(receive -> {
            if (receive.getIsRead().equals("0")) { //未读
                receive.setIsRead("1").setGmtReceive(new Date());
            }
        });
        boolean bUpdate = service.updateBatchById(Lists.newArrayList(receiveList));
        return bUpdate ? CommonResult.ok("更新成功") : CommonResult.error("更新失败");
    }


}
